package com.powerunion.datacollection.web.struts;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.powerunion.datacollection.model.query.TargetQuery;
import com.powerunion.datacollection.service.TargetFieldsManager;
import com.powerunion.datacollection.service.TargetManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.StringUtils;
import com.powerunion.util.log.LogHelper;

public class TargetAction extends DispatchAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(TargetAction.class);
	private TargetManager tgManager = null;
	
	public TargetAction() {
		super();
		this.tgManager = new TargetManager();
	}
	
	public void finalize() throws Throwable {
		this.tgManager = null;
		super.finalize();
	}
	
	public ActionForward save (ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {
		
		String saveStr = request.getParameter("formData");

		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("指标信息定义:"+saveStr);
			
			String id = this.tgManager.save(saveStr);
			
	        if(id != null && !id.equals("")) {
	        	response.getWriter().write("{success:true,data:'"+id+"'}");
	        }else{
	        	response.getWriter().write("{failure:true}");
	        }
			
			transaction.commit();
		} catch (Exception e) {
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}

		return null;
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String categoryId = request.getParameter("id");
		TargetQuery query = new TargetQuery();
		query.setCategoryId(categoryId);
		
        String startStr = request.getParameter("start")==null?"0":request.getParameter("start");
        String limitStr = request.getParameter("limit")==null?"28":request.getParameter("limit");
        
        int start = Integer.parseInt(startStr);
        int limit = Integer.parseInt(limitStr);
		
		String result = this.tgManager.getTargets(query,start,limit);
		logger.debug("Targets:"+result);
		response.setContentType("text/json;charset=utf-8");
		try{
			response.getWriter().print(result);
		}catch(Exception e) {
			logger.error("输出json失败",e);
			response.getWriter().write("{failure:true}");
		}
		return null;
	}
	
	public ActionForward getTargetDetails(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String targetId = request.getParameter("targetId");
		
		String result  = this.tgManager.getTargetDetails(targetId);
		logger.debug("getTargetDetails:"+result);
		response.setContentType("text/json;charset=utf-8");
		try{
			response.getWriter().write(result);
		}catch(Exception e) {
			logger.error("输出json失败",e);
			response.getWriter().write("{failure:true}");
		}
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String[] ids = StringUtils.split(request.getParameter("codes"), ",");
		
		Transaction transaction = null;

		response.setContentType("text/json;charset=utf-8");
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean flag = this.tgManager.delete(ids);

			if (flag == true) {
				response.getWriter().print("{success:true}");
			} else {
				response.getWriter().write("{failure:true}");
			}
			transaction.commit();
		} catch (Exception e) {
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		return null;
	}
		
	public ActionForward loadInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String id = request.getParameter("id");
		response.setContentType("text/json;charset=utf-8");
		String data = this.tgManager.loadInfo(id);
		logger.debug("loadInfo the Target:"+data);
    	response.getWriter().print(data);
		return null;
	}
	
	public ActionForward getTargetTree(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String paraSeq =  request.getParameter("id");	

		JSONArray jsonArray = this.tgManager.getTargetsTree(paraSeq);

		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(jsonArray);
		} catch (IOException e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	
	public ActionForward getSelectTargetsTree(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String paraSeq =  request.getParameter("id");	
		int flag =  Integer.parseInt(request.getParameter("flag"));	

		JSONArray jsonArray = null;
		
		if(flag == 0){
			jsonArray = this.tgManager.getSelectTargetsTree(paraSeq);
		}else if(flag == 1){
			jsonArray = this.tgManager.getTargetFieldTree(paraSeq);
		}

		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(jsonArray);
		} catch (IOException e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	
	/**
	 * 保存指标类别下统一的指标扩展值字段
	 * 该类别下的指标统一拥有定义的扩展值字段
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward saveTargetFields (ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {
		
		String saveStr = request.getParameter("formData");
		String categoryId = request.getParameter("categoryId");
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("指标扩展值字段信息定义:"+saveStr);
			TargetFieldsManager tfm = new TargetFieldsManager();
			boolean isuccess = tfm.save(saveStr, categoryId);
			
	        if(isuccess) {
	        	response.getWriter().write("{success:true}");
	        }else{
	        	response.getWriter().write("{failure:true}");
	        }
			
			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}

		return null;
	}
	
	public ActionForward getTargetFields(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String categoryId = request.getParameter("categoryId");
		TargetFieldsManager tfm = new TargetFieldsManager();
		String result = tfm.getTargetFields(categoryId);
		logger.debug("TargetFields:"+result);
		response.setContentType("text/json;charset=utf-8");
		try{
			response.getWriter().print(result);
		}catch(Exception e) {
			logger.error("输出json失败",e);
			response.getWriter().write("{failure:true}");
		}
		return null;
	}
	
}
